package main

import (
	"runtime"
	"time"
	"fmt"
	"io/ioutil"
	"encoding/json"
	"strconv"
	"bytes"
	"net/http"
	"net/url"
	"crypto/md5"
	"encoding/hex"
	"strings"
	"os"
)

type Config struct {
	Mysql struct{
		Read struct{
			Host string
			Username string
			Password string
			Dbname string
			Charset string
		}
		Write struct{
			Host string
			Username string
			Password string
			Dbname string
			Charset string
		}
	      }
	Redis  struct{
		Hosts []string
	      }
}

var DockerId string

func main() {
	//获取docker_id
	DockerId = getDockerId()
	//使用上多核
	runtime.GOMAXPROCS(runtime.NumCPU())
	//等待整分时才开始工作
	checkWholeMinite()
	//工作
	tick_10 := time.NewTicker(time.Second*10)
	tick_60 := time.NewTicker(time.Second*60)
	for {
		StrNowTime := getStrNowTime()
		select {
			case <-tick_10.C:
				go DoCronJob(StrNowTime)
			case <-tick_60.C:
				go DoAlarm()
				go DoMonitor()
		}
	}

	os.Getpid()
}

func getStrNowTime() string{
	t := time.Now()
	second := t.Second()
	minute := t.Minute()
	hour := t.Hour()
	day := t.Day()
	month := int(t.Month())
	week := int(t.Weekday())

	BufNowTime := bytes.Buffer{}
	BufNowTime.WriteString(strconv.Itoa(second))
	BufNowTime.WriteString(" ")
	BufNowTime.WriteString(strconv.Itoa(minute))
	BufNowTime.WriteString(" ")
	BufNowTime.WriteString(strconv.Itoa(hour))
	BufNowTime.WriteString(" ")
	BufNowTime.WriteString(strconv.Itoa(day))
	BufNowTime.WriteString(" ")
	BufNowTime.WriteString(strconv.Itoa(month))
	BufNowTime.WriteString(" ")
	BufNowTime.WriteString(strconv.Itoa(week))

	return BufNowTime.String()

}

func checkWholeMinite() bool{
	for {
		theTime := time.Now().Second()
		if(theTime == 0) {
			break;
		}
		time.Sleep(time.Second)
	}
	return true
}


func StrTimeToUnix(StrTime string) int64{
	loc, _ := time.LoadLocation("Local")
	//重要：获取时区
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", StrTime, loc) //使用模板在对应时区转化为time.time类型
	return theTime.Unix()
}

//获取配置信息
func GetConfig() Config {
	config_json, _ := ioutil.ReadFile("jobs_config.json")
	var config Config
	json.Unmarshal([]byte(config_json), &config)
	return config
}

//获取docker_id
func getDockerId() (string) {
	//TODO
	return "1"
}
func sendMessage(phoneCode string,message string) {
	httpUrl := "http://sms.51talk.com/Api/Sms/SendSmsNotice?"+phoneCode
	nowTime := time.Now().Format("2006-01-02 15:04:05")

	postData := url.Values{
		"mobile": {phoneCode},
		"msg":{message},
		"queue":{"0"},
		"send_time":{nowTime},
		"sms_id":{"0"},
		"sms_type":{"2"},
		"type":{"sys_notice"},
		"user_id": {"0"}}

	secretkey := "EGfAJFp^NGX$kK3!@e7pijEdMOaftwTz";
	sign := strings.ToUpper(md5Encode(md5Encode(url.QueryEscape(phoneCode+message+"0"+nowTime+"02sys_notice0"))+secretkey));

	postData.Add("sign",sign)

	resp, err := http.PostForm(httpUrl,
		postData)
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}

	if "ok" == string(body){

	}
}

func md5Encode(clearText  string) string{
	h := md5.New()
	h.Write([]byte(clearText)) // 需要加密的字符串为 sharejs.com
	return hex.EncodeToString(h.Sum(nil))
}

//错误log
func ErrorLog(err error) {
	if err != nil {
		fmt.Printf(time.Now().String() + " error:" + err.Error() + "\n")
	}
}
